"""
Video exporter for creating video presentations from Markdown content.

Integrates animation, TTS, and video composition into a complete pipeline.
"""

import asyncio
import os
from pathlib import Path
from typing import Dict, List, Optional, Any

from ...parser.content_types import DocumentStructure
from ...script.script_generator import ScriptGenerator, PresentationScript
from ...audio.tts.edge_tts import EdgeTTSEngine, TTSConfig, TTSRequest
from ...export.formats.html_exporter import HTMLExporter
from ...video.timeline import VideoTimeline, VideoConfig
from ...video.composer import VideoComposer
from ...script.subtitle_generator import SubtitleGenerator
from ...utils.exceptions import MD2PPTError


class VideoExporter:
    """Exports presentations to video format with animations and narration."""
    
    def __init__(self, 
                 video_config: Optional[VideoConfig] = None,
                 tts_config: Optional[TTSConfig] = None,
                 html_theme: str = "white"):
        """
        Initialize video exporter.
        
        Args:
            video_config: Video generation configuration
            tts_config: TTS configuration for narration
            html_theme: HTML theme for presentation
        """
        self.video_config = video_config or VideoConfig()
        self.tts_config = tts_config or TTSConfig()
        self.html_theme = html_theme
        
        # Initialize components
        self.script_generator = ScriptGenerator(language="zh-CN", style="conversational")
        self.tts_engine = EdgeTTSEngine()
        self.html_exporter = HTMLExporter(theme=html_theme)
        self.video_composer = VideoComposer(self.video_config)
        self.subtitle_generator = SubtitleGenerator()
        
        self._temp_files: List[str] = []
    
    async def export(self, 
                   doc_structure: DocumentStructure,
                   output_path: str,
                   generate_narration: bool = True,
                   background_music: Optional[str] = None,
                   create_preview: bool = False) -> Dict[str, str]:
        """
        Export document to video format.
        
        Args:
            doc_structure: Parsed document structure
            output_path: Output video file path
            generate_narration: Whether to generate TTS narration
            background_music: Optional background music file
            create_preview: Whether to create a preview video
            
        Returns:
            Dictionary with paths to generated files
        """
        try:
            print("🎬 开始视频导出流程...")
            
            # Step 1: Generate presentation script
            print("📜 生成演示脚本...")
            presentation_script = self.script_generator.generate_script(doc_structure)
            print(f"   脚本时长: {presentation_script.total_duration:.1f} 秒")
            print(f"   幻灯片数: {presentation_script.total_slides}")
            
            # Step 2: Generate TTS audio files
            audio_files = {}
            if generate_narration:
                print("🎤 生成TTS语音...")
                audio_files = await self._generate_tts_audio(presentation_script)
                print(f"   生成了 {len(audio_files)} 个音频文件")
            
            # Step 3: Export HTML presentation
            print("🌐 导出HTML演示...")
            html_path = self._get_temp_path("presentation.html")
            self.html_exporter.export(doc_structure, html_path)
            
            # Step 4: Create video timeline
            print("⏱️ 创建视频时间轴...")
            timeline = VideoTimeline(self.video_config)
            timeline.create_from_script(presentation_script, audio_files)
            timeline.optimize_timeline()
            
            print(f"   {timeline.get_timeline_summary()}")
            
            # Step 5: Generate subtitles
            print("📺 生成字幕文件...")
            subtitles = self.subtitle_generator.generate_subtitles(presentation_script)
            srt_path = self._get_output_path(output_path, ".srt")
            self.subtitle_generator.save_srt_file(subtitles, srt_path)
            
            # Step 6: Compose final video
            print("🎞️ 合成最终视频...")
            video_path = await self.video_composer.compose_video(
                html_path, timeline, output_path, background_music
            )
            
            # Step 7: Create preview if requested
            preview_path = None
            if create_preview:
                print("🎬 创建预览视频...")
                preview_path = self._get_output_path(output_path, "_preview.mp4")
                preview_path = await self.video_composer.create_preview_video(
                    html_path, timeline, preview_path, max_duration=30.0
                )
            
            # Collect results
            results = {
                "video": video_path,
                "html": html_path,
                "subtitles": srt_path,
                "timeline": timeline.export_timeline_data()
            }
            
            if preview_path:
                results["preview"] = preview_path
            
            if audio_files:
                results["audio_files"] = audio_files
            
            print("✅ 视频导出完成!")
            return results
            
        except Exception as e:
            await self._cleanup_temp_files()
            if isinstance(e, VideoExportError):
                raise
            else:
                raise VideoExportError(f"Video export failed: {e}")
    
    async def _generate_tts_audio(self, script: PresentationScript) -> Dict[int, str]:
        """Generate TTS audio files for each script segment."""
        audio_files = {}
        
        for segment in script.segments:
            if segment.content.strip():
                print(f"   合成第 {segment.slide_number} 页语音...")
                
                # Create TTS request
                request = TTSRequest(
                    text=segment.content,
                    config=self.tts_config,
                    output_path=self._get_temp_path(f"audio_slide_{segment.slide_number}.mp3")
                )
                
                try:
                    audio_path = await self.tts_engine.synthesize(request)
                    audio_files[segment.slide_number] = audio_path
                    
                    # Check file size
                    if os.path.exists(audio_path):
                        file_size = os.path.getsize(audio_path)
                        print(f"     ✅ {file_size} 字节")
                    
                except Exception as e:
                    print(f"     ❌ TTS失败: {e}")
                    continue
        
        return audio_files
    
    def create_video_config_preset(self, preset: str = "youtube") -> VideoConfig:
        """Create video configuration presets for different platforms."""
        presets = {
            "youtube": VideoConfig(
                width=1920, height=1080, fps=30,
                video_codec="libx264", bitrate="5M",
                slide_duration=4.0, transition_duration=0.5
            ),
            "tiktok": VideoConfig(
                width=1080, height=1920, fps=30,  # Vertical
                video_codec="libx264", bitrate="3M",
                slide_duration=3.0, transition_duration=0.3
            ),
            "bilibili": VideoConfig(
                width=1920, height=1080, fps=60,
                video_codec="libx264", bitrate="8M",
                slide_duration=5.0, transition_duration=0.8
            ),
            "wechat_video": VideoConfig(
                width=1280, height=720, fps=25,
                video_codec="libx264", bitrate="2M",
                slide_duration=4.0, transition_duration=0.4
            ),
            "4k": VideoConfig(
                width=3840, height=2160, fps=30,
                video_codec="libx264", bitrate="15M",
                slide_duration=6.0, transition_duration=1.0
            ),
            "preview": VideoConfig(
                width=1280, height=720, fps=24,
                video_codec="libx264", bitrate="1M",
                slide_duration=2.0, transition_duration=0.2
            )
        }
        
        return presets.get(preset, presets["youtube"])
    
    def get_supported_platforms(self) -> List[Dict[str, Any]]:
        """Get information about supported video platforms."""
        return [
            {
                "name": "YouTube",
                "preset": "youtube",
                "resolution": "1920x1080",
                "aspect_ratio": "16:9",
                "recommended_fps": 30,
                "description": "标准YouTube视频格式"
            },
            {
                "name": "TikTok/抖音",
                "preset": "tiktok", 
                "resolution": "1080x1920",
                "aspect_ratio": "9:16",
                "recommended_fps": 30,
                "description": "竖屏短视频格式"
            },
            {
                "name": "B站",
                "preset": "bilibili",
                "resolution": "1920x1080", 
                "aspect_ratio": "16:9",
                "recommended_fps": 60,
                "description": "高帧率B站视频"
            },
            {
                "name": "微信视频号",
                "preset": "wechat_video",
                "resolution": "1280x720",
                "aspect_ratio": "16:9", 
                "recommended_fps": 25,
                "description": "微信视频号格式"
            },
            {
                "name": "4K高清",
                "preset": "4k",
                "resolution": "3840x2160",
                "aspect_ratio": "16:9",
                "recommended_fps": 30,
                "description": "4K超高清格式"
            }
        ]
    
    async def export_multiple_formats(self,
                                    doc_structure: DocumentStructure,
                                    output_dir: str,
                                    platforms: List[str],
                                    generate_narration: bool = True) -> Dict[str, Dict[str, str]]:
        """
        Export video in multiple platform formats.
        
        Args:
            doc_structure: Document structure
            output_dir: Output directory
            platforms: List of platform presets
            generate_narration: Whether to generate narration
            
        Returns:
            Dictionary mapping platform to export results
        """
        os.makedirs(output_dir, exist_ok=True)
        results = {}
        
        # Generate narration once for all formats
        presentation_script = self.script_generator.generate_script(doc_structure)
        audio_files = {}
        
        if generate_narration:
            print("🎤 生成通用TTS语音...")
            audio_files = await self._generate_tts_audio(presentation_script)
        
        # Export for each platform
        for platform in platforms:
            print(f"\n🎬 导出 {platform} 格式...")
            
            # Update video config for platform
            self.video_config = self.create_video_config_preset(platform)
            self.video_composer = VideoComposer(self.video_config)
            
            # Generate output path
            output_path = os.path.join(output_dir, f"{doc_structure.title}_{platform}.mp4")
            
            try:
                result = await self.export(
                    doc_structure, output_path, 
                    generate_narration=False,  # Use pre-generated audio
                    create_preview=False
                )
                
                # Use pre-generated audio files
                if audio_files:
                    # Update timeline with audio files
                    timeline = VideoTimeline(self.video_config)
                    timeline.create_from_script(presentation_script, audio_files)
                    
                    # Re-compose with audio
                    html_path = result["html"]
                    await self.video_composer.compose_video(html_path, timeline, output_path)
                
                results[platform] = result
                print(f"✅ {platform} 格式导出完成")
                
            except Exception as e:
                print(f"❌ {platform} 格式导出失败: {e}")
                continue
        
        return results
    
    def _get_temp_path(self, filename: str) -> str:
        """Get temporary file path."""
        import tempfile
        temp_path = os.path.join(tempfile.gettempdir(), filename)
        self._temp_files.append(temp_path)
        return temp_path
    
    def _get_output_path(self, base_path: str, suffix: str) -> str:
        """Get output path with different suffix."""
        base = Path(base_path)
        return str(base.with_suffix(suffix))
    
    async def _cleanup_temp_files(self):
        """Clean up temporary files."""
        for temp_file in self._temp_files:
            try:
                if os.path.exists(temp_file):
                    os.remove(temp_file)
            except Exception:
                pass
        self._temp_files.clear()
    
    def get_exporter_info(self) -> Dict[str, Any]:
        """Get information about video exporter capabilities."""
        return {
            "supported_platforms": self.get_supported_platforms(),
            "video_config": {
                "resolution": f"{self.video_config.width}x{self.video_config.height}",
                "fps": self.video_config.fps,
                "codec": self.video_config.video_codec
            },
            "features": [
                "tts_narration",
                "subtitle_generation", 
                "background_music",
                "multiple_formats",
                "preview_generation",
                "timeline_synchronization"
            ],
            "composer_info": self.video_composer.get_composer_info()
        }


class VideoExportError(MD2PPTError):
    """Raised when video export fails."""
    pass